<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <div id="app1">
        app1:
        <span data-bind="text:ko.$store.get('getName')"></span>
    </div>
    <div id="app4">
        app4:
        <input type="text" data-bind="value:name" />
        <button type="text" data-bind="click:changeName" >改变名字</button>
        <span data-bind="text:ko.$store.state.class.name"></span>
    </div>
    <hr>
    <div id="app2">
        app2:
        <ul data-bind="foreach:list" >
            <li data-bind="text:title" ></li>
        </ul>
    </div>
    <div id="app3">
        app3: 
        <button type="button" data-bind="click:vf.add" >添加</button>
        <span data-bind="text:count"></span>
    </div>

    <script type="text/javascript" src="./knockout-latest.debug.js" ></script>
    <script type="text/javascript" src="./flux.js"></script>
    <script>

        function ViewModel(){
            this.list = ko.observableArray();
            this.name = ko.observable('无名氏');
            this.count = ko.computed(function(){
                //必须用this，这个时候ko.$store还没创建完成，应该ko.computed创建时会执行一次此处
                //如果是子vm依赖主vm，还是可以用ko.$store的
                return this.list().length + '个数'; //需要对监控对象求值，否则computed不能有效
            },this);
        }

        var vm = new ViewModel(); 

        var fullVm = vm, index = 1;
        fullVm.vf={
            add: function(){
                ko.$store.dispatch('addClass',{title: 'title' + (index++)});
            }
        }

        var opt = {
            state: {
                class: vm
            },
            actions:{
                "setName":function(state, name){
                    state.class.name(name);
                },
                "addClass":function(state, classInfo){
                    state.class.list.push(classInfo);
                }
            },
            getters:{
                "getName":function(state){
                    return state.class.name;
                }
            }
        }
        flux.createStore(opt);

        var app1 = ko.applyBindings(fullVm, document.getElementById("app1"));
        var app2 = ko.applyBindings(fullVm, document.getElementById("app2"));
        var app3 = ko.applyBindings(fullVm, document.getElementById("app3"));
        //测试两个vm之间的依赖 解藕
        var app4 = ko.applyBindings({
            name: ko.observable(),
            changeName:function(data,event){
                ko.$store.dispatch('setName', this.name());
            }
        }, document.getElementById("app4"));


    </script>
</body>
</html>